package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.zhijian.medical.dao.local.ExperimentProcessMapper;
import com.zhijian.medical.entity.dto.ExperimentReportJcxmDataDto;
import com.zhijian.medical.entity.po.ExperimentProcess;
import com.zhijian.medical.entity.po.ExperimentProcessSample;
import com.zhijian.medical.entity.po.ExperimentReport;
import com.zhijian.medical.entity.vo.request.*;
import com.zhijian.medical.entity.vo.response.ExperimentProcessResultDetailVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessResultVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessVo;
import com.zhijian.medical.enums.ExperimentProcessSampleStatusEnum;
import com.zhijian.medical.enums.ExperimentProcessStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.PcrSampleStatusEnum;
import com.zhijian.medical.service.*;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 实验流程业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-04-06 22:09:16
 */
@Slf4j
@Service
public class ExperimentProcessServiceImpl implements ExperimentProcessService {

    @Autowired
    private ExperimentProcessMapper mapper;

    @Autowired
    private ExperimentProcessCsvService experimentProcessCsvService;

    @Autowired
    private ExperimentProcessKzyService experimentProcessKzyService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessResultService experimentProcessResultService;

    @Autowired
    private ExperimentProcessResultDetailService experimentProcessResultDetailService;

    @Autowired
    private ExperimentProcessSpecimenService experimentProcessSpecimenService;

    @Autowired
    private ExperimentReportService experimentReportService;

    @Override
    public ExperimentProcess selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public ExperimentProcessVo selectVoById(Long id) {
        ExperimentProcessVo experimentProcessVo = mapper.selectVoById(id);
        if (Objects.nonNull(experimentProcessVo)) {
            experimentProcessVo.setExperimentProcessSampleList(experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                    .experimentProcessId(id)
                    .mainType(ExperimentTypeEnum.PCR.getCode().byteValue())
                    .build()));
        }
        return experimentProcessVo;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
        experimentProcessCsvService.deleteByExperimentProcessId(id);
        experimentProcessResultDetailService.deleteByExperimentProcessId(id);
        experimentProcessKzyService.deleteByExperimentProcessId(id);
        experimentProcessResultService.deleteByExperimentProcessId(id);
        experimentProcessResultDetailService.deleteByExperimentProcessId(id);
        experimentProcessSpecimenService.deleteByExperimentProcessId(id);
    }

    @Override
    public Long insert(ExperimentProcess experimentProcess) {
        Date now = new Date();
        experimentProcess.setCreateTime(now);
        experimentProcess.setUpdateTime(now);
        return mapper.insert(experimentProcess) > 0 ? experimentProcess.getId() : 0L;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public Long insert(ExperimentProcessSaveOrUpdateVo experimentProcessSaveOrUpdateVo) {
        ExperimentProcess experimentProcess = new ExperimentProcess();
        BeanUtils.copyProperties(experimentProcessSaveOrUpdateVo, experimentProcess);
        experimentProcess.setStatus(ExperimentProcessStatusEnum.SJPZ.getCode().byteValue());
        //编号
        experimentProcess.setProcessNumber(String.format("FZpcr%s", DateUtil.format(new Date(), new SimpleDateFormat("yyyyMMddHHmmss"))));
        Long experimentProcessId = this.insert(experimentProcess);
        experimentProcessSaveOrUpdateVo.getSampleIds().forEach(s -> experimentProcessSampleService.updateByPrimaryKeySelective(ExperimentProcessSample.builder()
                .id(s)
                .experimentProcessId(experimentProcessId)
                //状态改为检测中
                .status(PcrSampleStatusEnum.JCZ.getCode().byteValue())
                .build()));
        return experimentProcessId;
    }

    @Override
    public boolean update(ExperimentProcess experimentProcess) {
        Date now = new Date();
        experimentProcess.setUpdateTime(now);
        return mapper.updateByPrimaryKey(experimentProcess) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(ExperimentProcess experimentProcess) {
        return mapper.updateByPrimaryKeySelective(experimentProcess) != 0;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean update(ExperimentProcessSaveOrUpdateVo experimentProcessSaveOrUpdateVo) {
        ExperimentProcess experimentProcess = new ExperimentProcess();
        BeanUtils.copyProperties(experimentProcessSaveOrUpdateVo, experimentProcess);
        boolean b = this.updateByPrimaryKeySelective(experimentProcess);
        if (b) {
            //先把之前的关联样本关系删掉
            experimentProcessSampleService.removeRelation(experimentProcess.getId(), ExperimentTypeEnum.PCR.getCode().byteValue());
            experimentProcessSaveOrUpdateVo.getSampleIds().forEach(s -> experimentProcessSampleService.updateByPrimaryKeySelective(ExperimentProcessSample.builder()
                    .id(s)
                    .experimentProcessId(experimentProcess.getId())
                    //状态改为检测中
                    .status(ExperimentProcessSampleStatusEnum.ING.getCode().byteValue())
                    .build()));

        }
        return b;
    }

    @Override
    public Integer count(ExperimentProcessSearchVo experimentProcessSearchVo) {
        return mapper.count(experimentProcessSearchVo);
    }

    @Override
    public List<ExperimentProcessVo> selectList(ExperimentProcessSearchVo experimentProcessSearchVo) {
        return mapper.selectList(experimentProcessSearchVo);
    }

    @Override
    public Page<ExperimentProcessVo> selectPage(ExperimentProcessSearchVo experimentProcessSearchVo) {
        //先直接查总数
        int count = count(experimentProcessSearchVo);
        //分页
        Page<ExperimentProcessVo> page = new Page<>(true, count, experimentProcessSearchVo.getPageNum(), experimentProcessSearchVo.getPageSize());
        experimentProcessSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<ExperimentProcessVo> responseVos = this.selectList(experimentProcessSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean createReport(Long experimentProcessId) {

        ExperimentProcess experimentProcess = this.selectById(experimentProcessId);
        AssertUtil.notNull(experimentProcess, "此实验流程不存在或者已被删除");
        Integer c = experimentProcessSpecimenService.count(ExperimentProcessSpecimenSearchVo.builder()
                .experimentProcessId(experimentProcessId)
                .build());
        AssertUtil.check(c == 0, "此实验还未上传临床标本标识和扩增位置");

        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .experimentProcessId(experimentProcessId)
                .build());
        AssertUtil.notNull(CollectionUtil.isEmpty(experimentProcessSampleVos), "此实验流程无任何样本");
        //分子病理号
        List<String> moleculePathologyNumberList = experimentProcessSampleVos.stream().map(ExperimentProcessSampleVo::getMoleculePathologyNumber).distinct().collect(Collectors.toList());


        List<ExperimentProcessResultVo> experimentProcessResultVos = experimentProcessResultService.selectList(ExperimentProcessResultSearchVo.builder()
                .experimentProcessId(experimentProcessId)
                .build());
        AssertUtil.check(CollectionUtil.isEmpty(experimentProcessResultVos), "此实验还未进行结果判定");
        //结果判定的病理号
        List<String> blhList = experimentProcessResultVos.stream().map(ExperimentProcessResultVo::getBlh).distinct().collect(Collectors.toList());
        boolean equalCollection = org.apache.commons.collections4.CollectionUtils.isEqualCollection(moleculePathologyNumberList, blhList);
        AssertUtil.check(!equalCollection, "实验结果与实验样本不匹配");


        //KRAS
        List<ExperimentProcessResultVo> krasExperimentProcessResultVos = experimentProcessResultService.selectList(ExperimentProcessResultSearchVo.builder()
                .experimentProcessId(experimentProcessId)
                .project(ExperimentTypeEnum.PCR.getProject().get(0))
                .build());
        List<ExperimentReport> krasExperimentReports = krasExperimentProcessResultVos.stream().map(experimentProcessResultVo -> {
            ExperimentReport experimentReport = new ExperimentReport();
            experimentReport.setExperimentProcessId(experimentProcessId);
            experimentReport.setFzblh(experimentProcessResultVo.getBlh());
            ExperimentProcessSampleVo experimentProcessSampleVo = experimentProcessSampleService.selectVoByMoleculePathologyNumber(experimentProcessResultVo.getBlh());
            if (Objects.nonNull(experimentProcessSampleVo)) {
                mergeToExperimentReportFromExperimentProcessSampleVo(experimentReport, experimentProcessSampleVo);
            }
            List<ExperimentProcessResultDetailVo> experimentProcessResultDetailVos = experimentProcessResultDetailService.selectList(ExperimentProcessResultDetailSearchVo.builder()
                    .resultId(experimentProcessResultVo.getId())
                    .build());
            if (CollectionUtil.isNotEmpty(experimentProcessResultDetailVos)) {
                List<ExperimentReportJcxmDataDto> experimentReportJcxmDataDtos = experimentProcessResultDetailVos.stream().map(experimentProcessResultDetailVo -> {
                    ExperimentReportJcxmDataDto experimentReportJcxmDataDto = new ExperimentReportJcxmDataDto();
                    experimentReportJcxmDataDto.setJcxm(ExperimentTypeEnum.PCR.getProject().get(0));
                    experimentReportJcxmDataDto.setJcdw(experimentProcessResultDetailVo.getFyk());
                    experimentReportJcxmDataDto.setJgms(experimentProcessResultDetailVo.getYyx());
                    experimentReportJcxmDataDto.setCtz(experimentProcessResultDetailVo.getNkct() + "");
                    experimentReportJcxmDataDto.setDrtctz(experimentProcessResultDetailVo.getCt3() + "");
                    experimentReportJcxmDataDto.setJcjg(experimentProcessResultDetailVo.getYyx());
                    return experimentReportJcxmDataDto;
                }).collect(Collectors.toList());
                experimentReport.setKrasdata(JsonUtil.toString(experimentReportJcxmDataDtos));
            }
            return experimentReport;
        }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(krasExperimentReports)) {
            experimentReportService.insertBatch(krasExperimentReports);
        }

        //NRAS
        List<ExperimentProcessResultVo> nrasExperimentProcessResultVos = experimentProcessResultService.selectList(ExperimentProcessResultSearchVo.builder()
                .experimentProcessId(experimentProcessId)
                .project(ExperimentTypeEnum.PCR.getProject().get(1))
                .build());
        List<ExperimentReport> nrasExperimentReports = nrasExperimentProcessResultVos.stream().map(experimentProcessResultVo -> {
            ExperimentReport experimentReport = new ExperimentReport();
            experimentReport.setExperimentProcessId(experimentProcessId);
            experimentReport.setFzblh(experimentProcessResultVo.getBlh());
            ExperimentProcessSampleVo experimentProcessSampleVo = experimentProcessSampleService.selectVoByMoleculePathologyNumber(experimentProcessResultVo.getBlh());
            if (Objects.nonNull(experimentProcessSampleVo)) {
                mergeToExperimentReportFromExperimentProcessSampleVo(experimentReport, experimentProcessSampleVo);
            }
            List<ExperimentProcessResultDetailVo> experimentProcessResultDetailVos = experimentProcessResultDetailService.selectList(ExperimentProcessResultDetailSearchVo.builder()
                    .resultId(experimentProcessResultVo.getId())
                    .build());
            if (CollectionUtil.isNotEmpty(experimentProcessResultDetailVos)) {
                List<ExperimentReportJcxmDataDto> experimentReportJcxmDataDtos = experimentProcessResultDetailVos.stream().map(experimentProcessResultDetailVo -> {
                    ExperimentReportJcxmDataDto experimentReportJcxmDataDto = new ExperimentReportJcxmDataDto();
                    experimentReportJcxmDataDto.setJcxm(ExperimentTypeEnum.PCR.getProject().get(1));
                    experimentReportJcxmDataDto.setJcdw(experimentProcessResultDetailVo.getFyk());
                    experimentReportJcxmDataDto.setJgms(experimentProcessResultDetailVo.getYyx());
                    experimentReportJcxmDataDto.setCtz(experimentProcessResultDetailVo.getNkct() + "");
                    experimentReportJcxmDataDto.setDrtctz(experimentProcessResultDetailVo.getCt3() + "");
                    experimentReportJcxmDataDto.setJcjg(experimentProcessResultDetailVo.getYyx());
                    return experimentReportJcxmDataDto;
                }).collect(Collectors.toList());
                experimentReport.setNrasdata(JsonUtil.toString(experimentReportJcxmDataDtos));
            }
            return experimentReport;
        }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(nrasExperimentReports)) {
            experimentReportService.insertBatch(nrasExperimentReports);
        }

        //BRAF
        List<ExperimentProcessResultVo> brafExperimentProcessResultVos = experimentProcessResultService.selectList(ExperimentProcessResultSearchVo.builder()
                .experimentProcessId(experimentProcessId)
                .project(ExperimentTypeEnum.PCR.getProject().get(2))
                .build());
        List<ExperimentReport> brafExperimentReports = brafExperimentProcessResultVos.stream().map(experimentProcessResultVo -> {
            ExperimentReport experimentReport = new ExperimentReport();
            experimentReport.setExperimentProcessId(experimentProcessId);
            experimentReport.setFzblh(experimentProcessResultVo.getBlh());
            ExperimentProcessSampleVo experimentProcessSampleVo = experimentProcessSampleService.selectVoByMoleculePathologyNumber(experimentProcessResultVo.getBlh());
            if (Objects.nonNull(experimentProcessSampleVo)) {
                mergeToExperimentReportFromExperimentProcessSampleVo(experimentReport, experimentProcessSampleVo);
            }
            List<ExperimentProcessResultDetailVo> experimentProcessResultDetailVos = experimentProcessResultDetailService.selectList(ExperimentProcessResultDetailSearchVo.builder()
                    .resultId(experimentProcessResultVo.getId())
                    .build());
            if (CollectionUtil.isNotEmpty(experimentProcessResultDetailVos)) {
                List<ExperimentReportJcxmDataDto> experimentReportJcxmDataDtos = experimentProcessResultDetailVos.stream().map(experimentProcessResultDetailVo -> {
                    ExperimentReportJcxmDataDto experimentReportJcxmDataDto = new ExperimentReportJcxmDataDto();
                    experimentReportJcxmDataDto.setJcxm(ExperimentTypeEnum.PCR.getProject().get(2));
                    experimentReportJcxmDataDto.setJcdw(experimentProcessResultDetailVo.getFyk());
                    experimentReportJcxmDataDto.setJgms(experimentProcessResultDetailVo.getYyx());
                    experimentReportJcxmDataDto.setCtz(experimentProcessResultDetailVo.getNkct() + "");
                    experimentReportJcxmDataDto.setDrtctz(experimentProcessResultDetailVo.getCt3() + "");
                    experimentReportJcxmDataDto.setJcjg(experimentProcessResultDetailVo.getYyx());
                    return experimentReportJcxmDataDto;
                }).collect(Collectors.toList());
                experimentReport.setBrafdata(JsonUtil.toString(experimentReportJcxmDataDtos));
            }
            return experimentReport;
        }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(brafExperimentReports)) {
            experimentReportService.insertBatch(brafExperimentReports);
        }
        return true;
    }

    /**
     * 把样本管理的数据复制到报告里
     *
     * @param target
     * @param source
     */
    private void mergeToExperimentReportFromExperimentProcessSampleVo(ExperimentReport target, ExperimentProcessSampleVo source) {
        target.setName(source.getName());
        target.setSex(source.getSex());
        target.setReceiveDate(DateUtil.parse(source.getReceiveDate(), new SimpleDateFormat("yyyy-MM-dd HH:mm")));
        target.setHospital(source.getHospital());
        target.setInfectedPatch(source.getInfectedPatch());
        target.setKb(source.getKb());
        target.setDoctor(source.getDoctor());
        target.setMzh(source.getMzh());
        target.setCh(source.getCh());
        target.setZyh(source.getZyh());
        target.setBlh(source.getConventionPathologyNumber());
    }

}